package com.ruoyi.project.relation.service.impl;

import java.util.*;

import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.relation.domain.builder.BusinessLinkQOBuilder;
import com.ruoyi.project.relation.domain.dto.BusinessRelationDO;
import com.ruoyi.project.relation.service.IBusinessRelationService;
import com.ruoyi.project.wb.utils.TokenUserUtils;
import org.shoukaiseki.aqoeous.config.Validator;
import org.shoukaiseki.common.utils.AssertMessageVirtualException;
import org.shoukaiseki.common.utils.BooleanUtils;
import org.shoukaiseki.common.utils.NumberUtils;
import org.shoukaiseki.common.utils.StringUtils;
import org.shoukaiseki.common.logger.Logger;
import org.shoukaiseki.common.logger.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import com.ruoyi.project.relation.mapper.BusinessLinkMapper;
import com.ruoyi.project.relation.domain.BusinessLink;
import com.ruoyi.project.relation.domain.qo.BusinessLinkQO;
import com.ruoyi.project.relation.service.IBusinessLinkService;
import org.springframework.validation.BeanPropertyBindingResult;

import javax.annotation.Resource;

/**
 * 业务链路Service业务层处理
 *
 * @author wb
 * @date 2021-03-28
 */
@Service
public class BusinessLinkServiceImpl implements IBusinessLinkService
{
    public static final Logger logger = LoggerFactory.getLogger(BusinessLinkServiceImpl.class);

    @Autowired
    private BusinessLinkMapper businessLinkMapper;

    @Autowired
    private IBusinessRelationService businessRelationService;

    @Resource
    private Validator validator;

    /**
     * 添加链路,如果父级有多条链路则也会根据链路增加
     * @param currentBusiness
     * @param parentBusiness
     * @return
     */
    @Transactional
    @Override
    public void addLink(BusinessRelationDO currentBusiness, BusinessRelationDO parentBusiness) {
        SysUser user = TokenUserUtils.getUser();
        Date nowDate = DateUtils.getNowDate();
        BusinessLink businessLink ;
        validator.validate(currentBusiness,new BeanPropertyBindingResult(currentBusiness,"currentBusiness" ),true);


        if (parentBusiness !=null) {
            businessRelationService.addMultipleInterrelate(currentBusiness,parentBusiness);
            List<BusinessLink> inventoryBomLinkList = selectParentTreeByBusinessRelationDO(parentBusiness,null);
            //父级不存在,新增父级为顶级目录
            if (StringUtils.isEmpty(inventoryBomLinkList)) {
                addRootLink(parentBusiness);
                businessLink = BusinessLinkQOBuilder.newBusinessLinkQO()
                        .sourceOwner(currentBusiness)
                        .ancestorOwner(parentBusiness)
                        .level(1)
                        .buildBusinessLink();
//                BaseEntity.setCreate(businessLink,user.getUserId(),user.getUserName(), nowDate);
                insertBusinessLink(businessLink);

                //添加自链接
                addSelfLink(currentBusiness,2);
                return;
            }else{
                for (BusinessLink businessLinkTmp : inventoryBomLinkList) {
                    businessLink = BusinessLinkQOBuilder.newBusinessLinkQO()
                            .sourceOwner(currentBusiness)
                            .ancestorOwnerId(businessLinkTmp.getAncestorOwnerId())
                            .ancestorOwnerName(businessLinkTmp.getAncestorOwnerName())
                            .ancestorOwnerType(businessLinkTmp.getAncestorOwnerType())
                            .level(businessLinkTmp.getLevel())
                            .buildBusinessLink();
                    insertBusinessLink(businessLink);
                    if(BooleanUtils.isTrue(businessLinkTmp.getSelfLinkFlag())){
                        //添加自链接
                        addSelfLink(currentBusiness,businessLinkTmp.getLevel()+1);
                    }else{
                        //添加祖级关联
                        businessRelationService.addMultipleInterrelate(currentBusiness,new BusinessRelationDO(businessLinkTmp.getAncestorOwnerName(),businessLinkTmp.getAncestorOwnerType(),businessLinkTmp.getAncestorOwnerId()));
                    }
                }
            }



//            businessLink = new InventoryBomLink();
//            businessLink.setSourceBomId(parentBusiness.getInventoryBomId());
//            businessLink.setSourceOwnerId(parentBusiness.getOwnerId());
//            businessLink.setSourceOwnerName(parentBusiness.getOwnerName());
//            businessLink.setAncestorBomId(parentBusiness.getInventoryBomId());
//            businessLink.setAncestorOwnerName(parentBusiness.getOwnerName());
//            businessLink.setAncestorOwnerId(parentBusiness.getOwnerId());
//            BaseEntity.setCreate(businessLink,user.getUserId(),user.getUserName(), nowDate);
//            businessLinkMapper.insertInventoryBomLink(businessLink);
            return;
        }
        //最顶级,添加自身为最顶级
        addRootLink(currentBusiness);
    }


    /**
     * 添加自链接
     * @param currentBusiness
     */
    @Transactional
    @Override
    public void addSelfLink(BusinessRelationDO currentBusiness, int level){
        SysUser user=TokenUserUtils.getUser();
        Date nowDate = DateUtils.getNowDate();
        validator.validate(currentBusiness,new BeanPropertyBindingResult(currentBusiness,"currentBusinessDO" ),true);

        BusinessLink businessLink ;
        businessLink = BusinessLinkQOBuilder.newBusinessLinkQO()
                .sourceOwner(currentBusiness)
                .ancestorOwner(currentBusiness)
                .level(level)
                .selfLinkFlag(1)
                .buildBusinessLink();
//        BaseEntity.setCreate(businessLink,user.getUserId(),user.getUserName(), nowDate);
        insertBusinessLink(businessLink);
    }

    /**
     * 添加顶级链接
     * @param currentBusiness
     */
    @Transactional
    @Override
    public void addRootLink(BusinessRelationDO currentBusiness){
        addSelfLink(currentBusiness,1);
    }

    /**
     * 获取父级树列表
     * @param businessRelationDO
     * @param selfLinkFlag          是否需要增加自链接标志进行筛选,null 显示所有,true:只显示自链接的,false:只显示不是自链接的
     */
    @Override
    public List<BusinessLink> selectParentTreeByBusinessRelationDO(BusinessRelationDO businessRelationDO, Boolean selfLinkFlag){
        BusinessLinkQO businessLinkQO = BusinessLinkQOBuilder.newBusinessLinkQO()
                .sourceOwner(businessRelationDO)
                .build();
        //如果需要进行子链接筛选
        if(selfLinkFlag!=null){
            businessLinkQO.setSelfLinkFlag(selfLinkFlag?1:0);
        }
        return businessLinkMapper.selectParentTreeList(businessLinkQO);
    }


//    /**
//     * 精确查询业务链路列表,用于逻辑关联表处理
//     *
//     * @param businessLink 业务链路
//     * @return 业务链路集合
//     */
//    public List<BusinessLink> exactQueryBusinessLinkList(BusinessLink businessLink)
//    {
//        return businessLinkMapper.exactQueryBusinessLinkList(businessLink);
//    }


    /**
     * 新增业务链路
     *
     * @param businessLink 业务链路
     * @return 主键
     */
    @Transactional
    @Override
    public void insertBusinessLink(BusinessLink businessLink)
    {

        SysUser user = TokenUserUtils.getUser();
        Date nowDate = DateUtils.getNowDate();
        //不需要验证
//        BusinessLink businessLinkSO=BusinessLinkQOBuilder.newBusinessLinkQO()
//                .sourceOwnerName(businessLink.getSourceOwnerName())
//                .sourceOwnerType(businessLink.getSourceOwnerType())
//                .sourceOwnerId(businessLink.getSourceOwnerId())
//                .ancestorOwnerName(businessLink.getAncestorOwnerName())
//                .ancestorOwnerType(businessLink.getAncestorOwnerType())
//                .ancestorOwnerId(businessLink.getAncestorOwnerId())
//                .level(businessLink.getLevel())
//                .buildBusinessLink();
//        List<BusinessLink> businessLinkList = businessLinkMapper.exactQueryBusinessLinkList(businessLinkSO);
//        BusinessLink businessLinkTmp = businessLinkList.stream().findFirst().orElse(null);
//        if(businessLinkTmp!=null){
//            if(BooleanUtils.isTrue(businessLinkTmp.getDelFlag())){
//                businessLinkTmp.setDelFlag(0);
//                BaseEntity.setUpdate(businessLinkTmp,user, nowDate);
//                businessLinkMapper.updateBusinessLink(businessLinkTmp);
//                return ;
//            }
//            return ;
//        }

        BaseEntity.setCreate(businessLink,user,nowDate);
        businessLinkMapper.insertBusinessLink(businessLink);


        return ;
    }

//    /**
//     * 修改业务链路
//     *
//     * @param businessLink 业务链路
//     * @return 结果
//     */
//    @Transactional
//    @Override
//    public int updateBusinessLink(BusinessLink businessLink)
//    {
//        return businessLinkMapper.updateBusinessLink(businessLink);
//    }
//
    /**
     * 删除业务链路
     *
     * @param sourceBusiness
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBusinessLinkBySourceBusinessRelationDO(BusinessRelationDO sourceBusiness)
    {
        AssertMessageVirtualException.notEmpty(sourceBusiness.getOwnerName(),"ownerName不能为空");
        AssertMessageVirtualException.notNull(sourceBusiness.getOwnerId(),"ownerId不能为空");
        BusinessLinkQO businessLinkQO = BusinessLinkQOBuilder.newBusinessLinkQO()
                .sourceOwner(sourceBusiness)
                .build();

        businessRelationService.deleteBusinessRelationByBusinessRelationDO(sourceBusiness);

        int i= businessLinkMapper.deleteBusinessLinkByBusinessLinkQO(businessLinkQO);

        businessLinkQO = BusinessLinkQOBuilder.newBusinessLinkQO()
                .ancestorOwner(sourceBusiness)
                .build();
        i+= businessLinkMapper.deleteBusinessLinkByBusinessLinkQO(businessLinkQO);
        return i;
    }

}
